<template>
  <div class="book-management">
    <h2>图书管理</h2>
    <!-- 搜索功能区域 -->
      <div class="actions">
        <el-input v-model="search.bookNumber" placeholder="输入图书编号搜索" style="width: 200px; margin-right: 10px" />
        <el-input v-model="search.bookName" placeholder="输入图书名称搜索" style="width: 200px; margin-right: 10px" />
        <el-input v-model="search.bookAuthor" placeholder="输入作者搜索" style="width: 200px; margin-right: 10px" />
        <el-select v-model="search.bookStatus" placeholder="选择图书状态" style="width: 150px; margin-right: 10px" @change="fetchBooks">
          <el-option label="全部" :value="null" />
          <el-option label="可借" :value="'可借'" />
          <el-option label="不可借" :value="'不可借'" />
          <el-option label="已借出" :value="'已借出'" />
        </el-select>
        <el-button type="primary" @click="fetchBooks">搜索</el-button>
      </div>
      <!-- 批量操作功能区域 -->
      <div class="actions">
        <el-button type="primary" @click="openDialog('add')">新增图书</el-button>
        <el-button type="primary" :disabled="selectedBooks.length !== 1" @click="openDialog('update', selectedBooks[0])">编辑</el-button>
        <el-button type="danger" :disabled="selectedBooks.length === 0" @click="batchOperate('delete')">删除</el-button>
        <el-divider direction="vertical" />
        <el-dropdown>
          <el-button type="warning" :disabled="selectedBooks.length === 0">
            批量设置状态<el-icon class="el-icon--right"><arrow-down /></el-icon>
          </el-button>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item :disabled="selectedBooks.length === 0" @click="batchOperate('update', '可借' )">标记为可借</el-dropdown-item>
              <el-dropdown-item :disabled="selectedBooks.length === 0" @click="batchOperate('update', '不可借' )">标记为不可借</el-dropdown-item>
              <el-dropdown-item :disabled="selectedBooks.length === 0" @click="batchOperate('update', '已借出' )">标记为已借出</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    <!-- 图书表格显示 -->
    <el-table :data="bookData.content" row-key="bookId" :height="500" v-loading="loading" @selection-change="handleSelectionChange">
      <el-table-column type="selection" />
      <el-table-column type="index" label="序号" width="70" :index="indexMethod" />
      <el-table-column prop="bookNumber" label="图书编号" width="110px"/>
      <el-table-column prop="bookName" label="图书名称" />
      <el-table-column prop="bookCover" label="封面">
        <template #default="scope">
          <el-image :src="getImageUrl(scope.row.bookCover)" style="width: 100px; height: 100px" fit="cover" />
        </template>
      </el-table-column>
      <el-table-column prop="bookAuthor" label="作者" />
      <el-table-column prop="bookArea" label="区位" sortable/>
      <el-table-column prop="bookLocation" label="书架" sortable/>
      <el-table-column prop="bookDescription" label="简介">
        <template #default="scope">
          <el-tooltip effect="dark" :content="scope.row.bookDescription" placement="top">
            <div class="description">{{ scope.row.bookDescription }}</div>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column prop="bookType" label="类型" />
      <el-table-column prop="bookStatus" label="状态" sortable>
        <template #default="scope">
          <el-tag :type="getStatusType(scope.row.bookStatus)">{{ scope.row.bookStatus }}</el-tag>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->

      <div class="pagination-actions">
        <el-pagination background layout="prev, pager, next, sizes, jumper"
                       :total="bookData.totalElements" :page-size="pagination.size"
                       v-model:current-page="pagination.page" @update:currentPage="fetchBooks"
                       @size-change="handleSizeChange" />
      </div>


    <!-- 图书操作弹窗 -->
    <el-dialog title="图书操作" v-model="dialogVisible" width="600px" @close="clearBookForm">
      <el-form :model="bookForm">
        <el-form-item label="图书名称" required><el-input v-model="bookForm.bookName" placeholder="请输入图书名称" /></el-form-item>

        <el-form-item label="封面">
          <el-upload
              :on-change="handleFileChange"
              :before-upload="beforeFileUpload"
              :file-list="bookForm.fileList"
              :limit="1"
              list-type="picture-card"
              :auto-upload="false"
              :disabled="bookForm.fileList.length > 0">
            <el-icon><Plus /></el-icon>
            <template #file="{ file }">
              <div>
                <img
                    class="el-upload-list__item-thumbnail"
                    :src="file.url"
                    alt=""
                />
                <span class="el-upload-list__item-actions">
                  <span
                      class="el-upload-list__item-preview"
                      @click="handlePictureCardPreview(file)"
                  >
                    <el-icon><Zoom-in /></el-icon>
                  </span>
                  <span
                      v-if="!disabled"
                      class="el-upload-list__item-delete"
                      @click="handleRemove()"
                  >
                    <el-icon><Delete /></el-icon>
                  </span>
                </span>
              </div>
            </template>
          </el-upload>
        </el-form-item>

        <el-form-item label="作者" required><el-input v-model="bookForm.bookAuthor" placeholder="请输入作者" /></el-form-item>
        <el-form-item label="区位" required>
          <el-select v-model="bookForm.bookArea" placeholder="请选择区位">
            <el-option
                v-for="area in areas"
                :key="area.areaCodeId"
                :label="area.areaName"
                :value="area.areaName"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="类型" required>
          <el-select v-model="bookForm.bookType" placeholder="请选择图书类型">
            <el-option v-for="type in bookTypes" :key="type.typeId" :label="type.typeName" :value="type.typeName" />
          </el-select>
        </el-form-item>
        <el-form-item label="书架" required><el-input v-model="bookForm.bookLocation" placeholder="请输入书架" /></el-form-item>
        <el-form-item label="简介" required><el-input v-model="bookForm.bookDescription" type="textarea" rows="4" placeholder="请输入简介" /></el-form-item>
        <el-form-item label="状态" required>
          <el-select v-model="bookForm.bookStatus">
            <el-option label="可借" :value="'可借'" />
            <el-option label="不可借" :value="'不可借'" />
            <el-option label="已借出" :value="'已借出'" />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">保存</el-button>
      </div>
    </el-dialog>

    <!-- 图片预览对话框 -->
    <el-dialog v-model="dialogImageVisible" width="80%">
      <img :src="dialogImageUrl" alt="图片预览" style="width: 100%; height: auto;">
    </el-dialog>
  </div>
</template>

<script setup>
import {ref, onMounted} from 'vue';
import {ElMessage, ElMessageBox} from 'element-plus';
import http from '../utils/axios';
import { Plus, ZoomIn, Delete, ArrowDown } from '@element-plus/icons-vue';

const indexMethod = (index) => index + 1;
const areas = ref([]);
const bookData = ref({content: [], totalElements: 0});
const pagination = ref({page: 1, size: 10});
const search = ref({bookNumber: '', bookName: '', bookAuthor: '', bookArea: '', bookType: '', bookStatus: null});
const selectedBooks = ref([]);
const loading = ref(false);
const dialogVisible = ref(false);
const dialogImageVisible = ref(false);
const dialogImageUrl = ref('');
const bookTypes = ref([]); // 添加这一行

// 获取图书状态标签类型
const getStatusType = (status) => {
  const statusMap = {
    '可借': 'success',
    '不可借': 'danger',
    '已借出': 'warning'
  };
  return statusMap[status] || '';
};

// 删除图片
const handleRemove = () => {
  bookForm.value.fileList = [];
  bookForm.value.bookCover = null;
};

// 预览图片
const handlePictureCardPreview = (file) => {
  dialogImageUrl.value = file.url;
  dialogImageVisible.value = true;
};

// 打开图书操作弹窗
const openDialog = (type, book = null) => {
  if (type === 'add') {
    bookForm.value = {
      bookName: '',
      bookAuthor: '',
      bookArea: '',
      bookType: '',
      bookLocation: '',
      bookStatus: '可借',
      bookCover: null,
      fileList: []
    };
  } else if (type === 'update') {
    // 如果有图片封面，则设置回显的图片链接
    bookForm.value = {...book, bookCover: book.bookCover, fileList: []};
  }
  dialogVisible.value = true;
};

const bookForm = ref({
  bookId: null,
  bookName: '',
  bookAuthor: '',
  bookArea: '',
  bookType: '',
  bookLocation: '',
  bookStatus: '可借',
  bookDescription: '',
  bookCover: null,
  fileList: []
});

// 处理文件上传前的操作
const beforeFileUpload = (file) => {
  const isImage = file.type.startsWith('image/');
  if (!isImage) {
    ElMessage.error('只能上传图片文件');
  }
  return isImage;
};

// 文件变化处理
const handleFileChange = (_file, fileList) => {
  bookForm.value.fileList = fileList;
  if (fileList.length > 0) {
    const fileReader = new FileReader();
    fileReader.onload = (e) => {
      bookForm.value.bookCover = e.target.result;
    };
    fileReader.readAsDataURL(fileList[0].raw); // 读取图片文件作为DataURL
  } else {
    bookForm.value.bookCover = null; // 如果没有文件，则清空图片
  }
};

const fetchAreas = async () => {
  try {
    const response = await http.get('/Area/all');
    if (response.code === 200) { // 根据实际接口返回结构调整
      areas.value = response.data; // 如果返回的是数组直接赋值
    } else {
      ElMessage.error('获取馆区数据失败');
    }
  } catch (error) {
    ElMessage.error('获取馆区数据失败：' + error.message);
  }
};

// 提交表单
const handleSubmit = async () => {
  const formData = new FormData();
  formData.append('book',
      new Blob([JSON.stringify(bookForm.value)], {type: 'application/json'}));
  if (bookForm.value.fileList.length > 0) {
    formData.append('file', bookForm.value.fileList[0].raw);
  }
  try {
    const endpoint = bookForm.value.bookId ? '/book/update' : '/book/addBook';
    const response = await http[bookForm.value.bookId ? 'put' : 'post'](endpoint, formData);
    if (response.status) {
      ElMessage.success(response.data || '操作成功');
      dialogVisible.value = false;
      await fetchBooks();
    } else {
      ElMessage.error(response.message || '操作失败');
    }
  } catch (error) {
    ElMessage.error('操作失败：' + error.message);
  }
};

// 获取图书封面时避免缓存，确保刷新图片
const getImageUrl = (coverName) => {
  if (coverName) {
    return `http://localhost:8080/book/image/${coverName}?t=${new Date().getTime()}`;
  }
  return ''; // 如果没有封面，则返回空字符串
};

// 搜索图书
const fetchBooks = async () => {
  try {
    loading.value = true;
    const response = await http.post('/book/all', {
      page: pagination.value.page - 1,
      size: pagination.value.size,
      ...search.value
    });
    if (response.status) {
      bookData.value = response.data;
    } else {
      ElMessage.error(response.data || '获取图书列表失败');
    }
  } catch (error) {
    ElMessage.error('获取图书列表失败：' + error.message);
  } finally {
    loading.value = false;
  }
};

// 获取图书分类
const fetchBookTypes = async () => {
  try {
    const response = await http.get('/Type/all');
    if (response.status) {
      bookTypes.value = response.data;
    } else {
      ElMessage.error(response.data || '获取图书分类失败');
    }
  } catch (error) {
    ElMessage.error('获取图书分类失败：' + error.message);
  }
};

onMounted(() => {
  fetchBooks();
  fetchBookTypes();
  fetchAreas();
});

// 批量操作
const batchOperate = async (action, status = '') => {
  if (selectedBooks.value.length === 0) {
    ElMessage.error('请先选择图书');
    return;
  }
  const bookIds = selectedBooks.value.map((book) => book.bookId);
  try {
    if (action === 'delete') {
      await ElMessageBox.confirm('确认删除选中的图书？', '提示', {
        confirmButtonText: '删除',
        cancelButtonText: '取消',
        type: 'warning'
      });
      const response = await http.delete('/book/batch/delete', {data: {bookId: bookIds}});
      if (response.status) {
        ElMessage.success(response.data || '删除成功');
        await fetchBooks();
      } else {
        ElMessage.error(response.data || '删除失败');
      }
    } else if (action === 'update') {
      const response = await http.put('/book/batch/update/status', {bookIds, status});
      if (response.status) {
        ElMessage.success(response.data || '状态更新成功');
        await fetchBooks();
      } else {
        ElMessage.error(response.data || '更新失败');
      }
    }
  } catch (error) {
    ElMessage.error('操作失败：' + error.message);
  }
};

// 处理图书选择变化
const handleSelectionChange = (val) => {
  selectedBooks.value = val;
};

// 分页大小变化
const handleSizeChange = (size) => {
  pagination.value.size = size;
  pagination.value.page = 1;
  fetchBooks();
};

// 清除表单
const clearBookForm = () => {
  bookForm.value = {
    bookId: null,
    bookName: '',
    bookAuthor: '',
    bookArea: '',
    bookType: '',
    bookLocation: '',
    bookStatus: '可借',
    bookDescription: '',
    bookCover: null,
    fileList: []
  };
};
</script>

<style scoped>
.book-management {
  padding: 20px;
}

.actions {
  margin-top: 20px;
}

.pagination-actions {
  margin-top: 20px;
  padding: 10px;
}

.description {
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 4;
  line-clamp: 4;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: normal;
}
</style>
